/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.geektimes.http.server.jdk.servlet;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import org.geektimes.commons.reflect.util.ClassUtils;
import org.geektimes.http.server.WebServer;
import org.geektimes.http.server.jdk.servlet.adapter.ServletContextAdapter;
import org.geektimes.http.server.jdk.servlet.handler.SimpleServletHttpHandler;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import java.util.logging.Logger;

import static java.lang.Integer.getInteger;
import static java.lang.String.format;
import static java.lang.System.getProperty;

/**
 * Simple {@link Servlet} Http Server
 *
 * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
 * @since 1.0.0
 */
public class SimpleServletWebServer implements WebServer {

    public static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";

    private final Logger logger = Logger.getLogger( this.getClass().getName() );

    private final int port;

    private final String contextPath;

    private final File rootDirectory;

    private HttpServer httpServer;

    private ExecutorService executorService;

    private Future<?> future;

    public SimpleServletWebServer() {
        this( getInteger( "simple.http.server.port", 8080 ) );
    }

    public SimpleServletWebServer( int port ) {
        this( getProperty( "simple.http.server.path", "/" ), port );
    }

    public SimpleServletWebServer( String path, int port ) {
        this.contextPath = path;
        this.port = port;
        this.rootDirectory = initRootDirectory();
    }

    private File initRootDirectory() {
        File rootDirectory = new File( System.getProperty( "user.dir" ), ".servlet-web-server" );
        rootDirectory.mkdirs();
        return rootDirectory;
    }

    @Override
    public SimpleServletWebServer start( boolean sync ) throws IOException {

        httpServer = HttpServer.create( new InetSocketAddress( port ), 0 );

        SimpleServletHttpHandler httpHandler = new SimpleServletHttpHandler();

        HttpContext httpContext = httpServer.createContext( contextPath, httpHandler );

        ServletContext servletContext = adaptServletContext( httpContext );

        httpHandler.setServletContext( servletContext );

        initFilters( servletContext );

        initServlets( servletContext );

        executorService = ForkJoinPool.commonPool();

        httpServer.setExecutor( executorService );

        if ( sync ) {
            startHttpServer();
        } else {
            future = executorService.submit( this::startHttpServer );
        }

        return this;
    }

    private void initServlets( ServletContext servletContext ) {
        // 利用spring的机制，读取classpath*:org/geektimes/http/server/jdk/servlet/**/*.class 所有的类，处理有有@WebServlet注解的
        Consumer<Class> consumer = clazz ->{
            WebServlet webServlet = ClassUtils.findAnnotation( clazz, WebServlet.class );
            if ( webServlet != null ) {
                ServletRegistration.Dynamic dynamic = servletContext.addServlet( webServlet.name(), clazz );
                for ( String urlPattern : webServlet.urlPatterns() ) {
                    dynamic.addMapping( urlPattern.trim() );
                }
                dynamic.setLoadOnStartup( 1 );
            }
        };
        FindSuperClassUtils.findSubClassAndConsume(Servlet.class,null,consumer);
    }


    private void initFilters( ServletContext servletContext ) {
        // TODO
    }

    private ServletContext adaptServletContext( HttpContext httpContext ) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        return new ServletContextAdapter( httpContext, rootDirectory, classLoader );
    }

    private void startHttpServer() {
        logger.info( format( "Simple HTTP Server(port : %d, path : %s) is starting...%n", port, contextPath ) );
        httpServer.start();
    }

    @Override
    public SimpleServletWebServer stop() {
        logger.info( format( "Simple HTTP Server(port : %d, path : %s) is stopping...%n", port, contextPath ) );
        if ( future != null && !future.isDone() ) {
            future.cancel( true );
            executorService.shutdown();
        }

        httpServer.stop( 0 );
        logger.info( format( "Simple HTTP Server(port : %d, path : %s) is stopped...%n", port, contextPath ) );
        return this;
    }

}
